package com.meida.module.arc.provider.handler;

import com.meida.common.base.constants.CommonConstants;
import com.meida.common.base.service.WebSocketMsgService;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.module.arc.client.entity.ArcField;
import com.meida.module.arc.client.entity.ArcInfo;
import com.meida.module.arc.client.entity.ArcOriginal;
import com.meida.module.arc.provider.service.ArcFieldService;
import com.meida.module.arc.provider.service.ArcInfoService;
import com.meida.module.arc.provider.service.ArcOriginalService;
import com.meida.module.file.client.vo.OssSetting;
import com.meida.module.file.provider.oss.FileUploadUtil;
import com.meida.module.file.provider.oss.client.MioClient;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Scope("prototype")
public class HookUpHanlder {
    @Autowired
    private ArcOriginalService arcOriginalService;

    @Autowired
    @Lazy
    private ArcInfoService arcInfoService;

    @Autowired
    private ArcFieldService arcFieldService;

    @Autowired(required = false)
    private WebSocketMsgService webSocketMsgService;

    @Autowired
    private MioClient mioClient;
    @Autowired
    public ApplicationContext applicationContext;
    @Resource
    EsHandler esHandler;
    @Async
    public void hookUpSubmit(List<Item> files, Integer hookUpType, Long userId, Long categoryId, OssSetting ossSetting, String categoryName) {
        if (FlymeUtils.isNotEmpty(files)) {
            String bucketName = ossSetting.getBucket();
            List<String> removeList = new ArrayList<>();
            int fileIndex = 0;
            int fileTotal = files.size();
            //失败数量
            int failCount = 0;
            //成功数量
            int successCount = 0;
            for (Item item : files) {
                String objectName = item.objectName();
                Long fileSize = item.size();
                //判断是否是微服务
                Object object = applicationContext.getEnvironment().getProperty(CommonConstants.CLOUD_SERVER_KEY);
                String fileBasePath = "";
                if (FlymeUtils.isEmpty(object)) {
                    //单机版
                    fileBasePath += "已挂接/";
                }
                fileBasePath += FileUploadUtil.datePath() + "/";
                //原文件名
                String fileName = objectName.substring(objectName.lastIndexOf("/") + 1);
                //不带后缀的文件名
                String fileNameNoExtend = fileName.substring(0, fileName.lastIndexOf("."));
                //重命名文件
                String fileNewName = FlymeUtils.renameFile(fileName);
                String newObjName = fileBasePath + fileNewName;

                String arcNo = "";
                if (hookUpType.equals(1)) {
                    arcNo = fileNameNoExtend;
                }
                if (hookUpType.equals(2)) {
                    arcNo = objectName.substring(objectName.indexOf("/", 0) + 1, objectName.lastIndexOf("/"));
                }
                if (hookUpType.equals(3)) {
                    arcNo = objectName.substring(objectName.indexOf("/", 0) + 1, objectName.lastIndexOf("/") + 1);
                    arcNo = arcNo.replace("/", "");
                }
                if (FlymeUtils.isNotEmpty(arcNo)) {
                    //根据文件名查询
                    ArcInfo arcInfo = getArcInfo(arcNo, userId, categoryId);
                    if (FlymeUtils.isNotEmpty(arcInfo)) {
                        successCount++;
                        //拷贝文件
                        mioClient.copyObject(bucketName, objectName, bucketName, fileBasePath + fileNewName);
                        //添加原文档案
                        insertArcInfo(userId, categoryId, arcInfo, fileName, fileSize, "", newObjName, ossSetting);
                        //加入删除结合
                        removeList.add(objectName);
                    } else {
                        failCount++;
                    }
                } else {
                    failCount++;
                }
                fileIndex++;
                //发送挂接通知
                sendMessage(userId, objectName, fileIndex, fileTotal, categoryName, failCount, successCount);
            }
            if (FlymeUtils.isNotEmpty(removeList)) {
                //删除原文件
                mioClient.removeObjects(removeList);
            }
        }
    }

    private void sendMessage(Long userId, String fileName, Integer fileIndex, Integer fileTotal, String categoryName, Integer failCount, Integer successCount) {
        Map map = new HashMap(5);
        Integer surplusFileCount = fileTotal - fileIndex;
        BigDecimal percentage = new BigDecimal(fileIndex).divide(new BigDecimal(fileTotal), 2, RoundingMode.HALF_DOWN).multiply(new BigDecimal(100));
        map.put("successCount", successCount);
        map.put("failCount", failCount);
        map.put("fileName", fileName);
        map.put("percentage", percentage);
        map.put("fileIndex", fileIndex);
        map.put("fileTotal", fileTotal);
        map.put("categoryName", categoryName);
        map.put("surplusFileCount", surplusFileCount);
        map.put("hookUp", 1);
        if (fileIndex.equals(fileTotal)) {
            map.put("finish", 1);
        }
        webSocketMsgService.sendMessage(userId, 3, map);
    }

    public void insertArcInfo(Long userId, Long categoryId, ArcInfo arcInfo, String fileName, long fileSize, String filePath, String ossPath, OssSetting ossSetting) {
        if (FlymeUtils.isNotEmpty(arcInfo)) {
            String localPath = ossSetting.getFilePath() + "/" + ossSetting.getBucket() + "/" + ossPath;
            ArcOriginal arcOriginal = new ArcOriginal();
            arcOriginal.setArcInfoId(arcInfo.getArcInfoId());
            arcOriginal.setCategoryId(categoryId);
            arcOriginal.setQzId(arcInfo.getQzId());
            arcOriginal.setFileType(FileUploadUtil.getExtend(fileName));
            String contentType = MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
            arcOriginal.setFileContenttype(contentType);
            arcOriginal.setFileSize(fileSize);
            arcOriginal.setFileName(fileName);
            arcOriginal.setFilePath(mioClient.getBasePath() + ossSetting.getBucket() + "/" + filePath);
            arcOriginal.setOssPath(mioClient.getBasePath() + ossSetting.getBucket() + "/" + ossPath);
            arcOriginal.setLocalPath(localPath);
            arcOriginalService.save(arcOriginal);
            try {
                arcInfoService.updateOriginalCount(categoryId.toString(), arcInfo.getArcInfoId().toString(), 1);
                //保存全文索引//TODO 暂时屏蔽
                //arcOriginalRepository.save(arcOriginal);

                esHandler.saveEs(arcOriginal);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private ArcInfo getArcInfo(String arcNo, Long userId, Long categoryId) {
        ArcField arcField = arcFieldService.getArcField(categoryId);
        ArcInfo arcInfo = null;
        if (FlymeUtils.isNotEmpty(arcField)) {
            arcInfo = arcInfoService.getArcInfoByField(arcField, userId, arcNo, categoryId, false);
            System.out.println("自定义挂接################################" + arcNo);
        } else {
            arcInfo = arcInfoService.getArcInfoByArcNoAndCateGoryId(arcNo, categoryId);
        }
        return arcInfo;
    }


}
